# -*- coding: utf-8 -*-
# @Time    : 2021/3/2 16:20
# @Author  : AkromA
# @File    : dispatcher.py
# @Software: PyCharm
# @Info    : 调度方法

from db.db_conn import DBHandle
from house_crawler.get_computer_info import GetComputerInfo
from house_crawler.task_handle import task_update_begin, task_update_ending, task_update_fail
from house_crawler.ajk_esf_crawler import ajk_esf_main
from house_crawler.ajk_zf_crawler import ajk_zf_main


def dispatcher():
    # 连接数据库
    db_handle = DBHandle()
    # 从任务表中获取一条待执行的数据
    get_task_sql = "SELECT task_id, task_info FROM 08_task WHERE task_state = 1 LIMIT 1;"
    task_ = db_handle.select_sql(get_task_sql)
    db_handle.close_db()
    if len(task_) == 0:
        print("没有要执行的任务")
        return

    task_id = task_[0]['task_id']
    task_info = task_[0]['task_info'].split(',')
    my_ip = GetComputerInfo().get_myip()

    # 根据任务id更新对应任务状态并开始执行
    task_update_begin(task_id, my_ip)

    # 调用执行任务的代码
    city_short = task_info[1]       # 城市缩写
    district_param = task_info[0]   # 关键词
    city_code = task_info[2]        # 城市代码
    data_source = task_info[3]      # 数据来源
    rent_type =  task_info[4]       # 数据类型（0二手房1整租2合租）

    if rent_type == "0":
        flag = ajk_esf_main(city_short, district_param, city_code, data_source)
    elif rent_type == "1":
        flag = ajk_zf_main(city_short, district_param, city_code, data_source, "1")
    elif rent_type == "2":
        flag = ajk_zf_main(city_short, district_param, city_code, data_source, "2")
    else:
        flag = False

    # 如果顺利执行完成，则将任务状态更新为成功
    if flag:
        task_update_ending(task_id)

    # 如果没有执行完成，则将任务状态更新为失败
    if not flag:
        task_update_fail(task_id)


if __name__ == '__main__':
    dispatcher()
